angular.module('BaseControl')

.directive("multitab", [function() {
    return {
        restrict: "E",	// 指令是一个元素 (并非属性)，备选项有"A"、"E" 和 "C"， "M" ,分别代表attribute、element、class和comment（默认值为"A"）
        scope: {
            type: '@',
            visible: '@'
        },
        template:'<div style="display:{{display}};">' +
            '<div>' +
                '<ul class="nav nav-{{type || \'tabs\'}}" ng-class="{\'nav-stacked\': vertical, \'nav-justified\': justified}" ng-transclude></ul>' +
            '</div>' +
            '<div class="tab-content" style="border:solid #DDDDDD 1px;border-top-width: 0px;padding:5px;">' +
                '<div class="tab-pane" ng-repeat="tab in tabs" ng-class="{active: tab.active}" multitabcontent="tab">' +
                '</div>' +
            '</div>' +
        '</div>',
        replace: true,			// 使用模板替换原始标记
        transclude: true,		// 不复制原始HTML内容
        controller: ['$scope', function($scope){
            var ctrl = this,
                tabs = ctrl.tabs = $scope.tabs = [];

            ctrl.select = function(selectedTab) {
                angular.forEach(tabs, function(tab) {
                    if (tab.active && tab !== selectedTab) {
                        tab.active = false;
                        //tab.onDeselect();
                    }
                });
                selectedTab.active = true;
                //selectedTab.onSelect();
            };

            ctrl.addTab = function addTab(tab) {
                tabs.push(tab);

                if (tabs.length === 1) {
                    tab.active = true;
                } else if (tab.active) {
                    ctrl.select(tab);
                }
            };

            ctrl.removeTab = function removeTab(tab) {
                var index = tabs.indexOf(tab);

                if (tab.active && tabs.length > 1) {
                    var newActiveIndex = index == tabs.length - 1 ? index - 1 : index + 1;
                    ctrl.select(tabs[newActiveIndex]);
                }
                tabs.splice(index, 1);
            };
        }],
        link: function (scope, element, attrs) {
            scope.display = scope.visible != undefined && scope.visible.toLocaleLowerCase() == 'false' ? 'none' : '';

            scope.vertical = angular.isDefined(attrs.vertical) ? scope.$parent.$eval(attrs.vertical) : false;
            scope.justified = angular.isDefined(attrs.justified) ? scope.$parent.$eval(attrs.justified) : false;
        }
    }
}])

.directive("multitabitem", ['$parse', function($parse) {
    return {
        require: '^multitab',
        restrict: "E",	// 指令是一个元素 (并非属性)，备选项有"A"、"E" 和 "C"， "M" ,分别代表attribute、element、class和comment（默认值为"A"）
        scope: {
            active: '=?',
            heading: '@'
        },
        template:
            '<li ng-class="{active: active, disabled: !enabled}" style="display:{{visible == false ? "none" : ""}}">' +
                '<a ng-click="select()" multitabitemcontent>{{heading}}</a>' +
            '</li>',
        replace: true,			// 使用模板替换原始标记
        transclude: true,
        controller: function() {
            //Empty controller so other directives can require being 'under' a tab
        },
        compile: function(elm, attrs, transclude) {
            return function postLink(scope, elm, attrs, multitabCtrl) {
                scope.$watch('active', function(active) {
                    if (active) {
                        multitabCtrl.select(scope);
                    }
                });

                scope.enabled = true;
                if ( attrs.enabled ) {
                    scope.$parent.$watch($parse(attrs.enabled), function(value) {
                        scope.enabled = value != undefined ? value : true;
                    });
                }

                scope.select = function() {
                    if ( scope.enabled ) {
                        scope.active = true;
                    }
                };

                multitabCtrl.addTab(scope);
                scope.$on('$destroy', function() {
                    multitabCtrl.removeTab(scope);
                });

                scope.$transcludeFn = transclude;
            };
        }
    }
}])

.directive('multitabitemcontent', [function() {
    return {
        restrict: 'A',
        //require: '^multitabitem',
        link: function(scope, elm, attrs, tabCtrl) {
            scope.$watch('headingElement', function updateHeadingElement(heading) {
                if (heading) {
                    elm.html('');
                    elm.append(heading);
                }
            });
        }
    };
}])

.directive('multitabcontent', function() {
    return {
        restrict: 'A',
        require: '^multitab',
        link: function(scope, elm, attrs) {
            var tab = scope.$eval(attrs.multitabcontent);

            tab.$transcludeFn(tab.$parent, function(contents) {
                angular.forEach(contents, function(node) {
                    if (isTabHeading(node)) {
                        //Let tabHeadingTransclude know.
                        tab.headingElement = node;
                    } else {
                        elm.append(node);
                    }
                });
            });
        }
    };

    function isTabHeading(node) {
        return node.tagName &&  (
            node.hasAttribute('tab-heading') ||
            node.hasAttribute('data-tab-heading') ||
            node.tagName.toLowerCase() === 'tab-heading' ||
            node.tagName.toLowerCase() === 'data-tab-heading'
            );
    }
});
